import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Input, Text, Image} from '@tarojs/components'
import {ScenicGood, AppointmentItem} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {
  EXCHANGE_LIBRARY_DETAILS,
  EXCHANGE_LIBRARY_CODE_IS_ADEQUATE,
  EXCHANGE_LIBRARY_GET_EXCHANGE_CODE,
  EXCHANGE_LIBRARY_SHOW_EXCHANGE_CODE,
  CHECK_TICKET,
  BASE_URL,
  GET_IMG
} from '../../constants/api'
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './order.scss'
import './exchangeCode.scss'

interface Product extends ScenicGood {
  selected: boolean
}

interface StateType {
  listForm: any
  codeShow: boolean
  ticketList: any
}

export default class Order extends Component {
  state: StateType = {
    listForm: {},
    codeShow: false,
    ticketList: [],
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    if (process.env.TARO_ENV === "weapp") {
      Taro.hideShareMenu()
    }
  }

  async componentDidShow() {
    vcmonitor(this);
    const {uuid = ''} = Taro.getCurrentInstance().router.params
    this.uuid = uuid
    await this.initData()
  }
  uuid = ''
  btnDisabled = false

  // type:success兑换码展示成功后的显示
  async initData(type?) {
    Taro.showLoading({title: '加载中'})
    const res = await http.HPost<AppointmentItem>(EXCHANGE_LIBRARY_DETAILS, {uuid: this.uuid})
    let listForm = {}
    if (res.data) {
      listForm = res.data
      if (res.data.isTicket == 1 && !type) {
        const resShow = await http.HPost(EXCHANGE_LIBRARY_SHOW_EXCHANGE_CODE, {order_num: res.data.order_num})
        if (resShow.data) {
          this.setState({
            ticketList: resShow.data,
            codeShow: true
          })
        }
      }
      Taro.hideLoading()
    }
    this.setState({listForm})
  }

   submit() {
    const {listForm} = this.state
     if (listForm.isTicket == 1) {
       this.setState({
         codeShow: true
       })
       return
     }
    Taro.showModal({
      title: '确定兑换吗？',
      content: '兑换后将无法申请退款',
      cancelText: '取消',
      confirmText: '确定',
      success: async (ret) => {
        const params ={
          ticket_library_id: listForm.library_id,
          num: listForm.ticketNumber
        }
        if (ret.confirm) {
          /*查询码库是否充足*/
          const res = await http.HPost<AppointmentItem>(EXCHANGE_LIBRARY_CODE_IS_ADEQUATE, params)
          if (res.data) {
            if (!res.data.isOk) {
              Taro.showModal({
                title: '兑换失败！',
                content: res.data.message,
                showCancel: false,
                confirmText: '确定'
              })
            } else {
              const {listForm} = this.state
              const searchParams = {
                supplierId: listForm.supplier_id,
                ticket_library_id: listForm.library_id,
                goods_id: listForm.goods_id,
                order_num: listForm.order_num,
                num: listForm.ticketNumber,
              }
              /*核验核验码*/
              const retarr = []
              const errarr = []
              for (const i in listForm.ticketList) {
                const data = {
                  ext_keywords: '',
                  supplierId: listForm.supplier_id,
                  keywords: listForm.ticketList[i].ticket,
                  num: listForm.ticketList[i].can_check_num,
                  verification_srouce: 0
                }
                const ret = await http.HPost(CHECK_TICKET, data, true)
                if (ret.data) {
                  retarr.push(ret.data)
                } else {
                  errarr.push(ret.msg || ret.message)
                }
              }
              if (errarr.length > 0) {
                Taro.showModal({
                  title: '核销提示',
                  content: errarr.join('|'),
                  showCancel: false,
                  success: async (res) => {
                    /*核验核验码成功，查询关联的兑换码*/
                    const resGet = await http.HPost(EXCHANGE_LIBRARY_GET_EXCHANGE_CODE, searchParams)
                    if (!resGet) {
                      /*查询到关联的兑换码，开始显示兑换码*/
                      const resShow = await http.HPost(EXCHANGE_LIBRARY_SHOW_EXCHANGE_CODE, {order_num: listForm.order_num})
                      if (resShow.data) {
                        this.initData('success')
                        this.setState({
                          ticketList: resShow.data,
                          codeShow: true
                        })
                      }
                    }
                  }
                })
                return
              } else {
                /*核验核验码成功，查询关联的兑换码*/
                const resGet = await http.HPost(EXCHANGE_LIBRARY_GET_EXCHANGE_CODE, searchParams)
                if (!resGet) {
                  /*查询到关联的兑换码，开始显示兑换码*/
                  const resShow = await http.HPost(EXCHANGE_LIBRARY_SHOW_EXCHANGE_CODE, {order_num: listForm.order_num})
                  if (resShow.data) {
                    this.initData('success')
                    this.setState({
                      ticketList: resShow.data,
                      codeShow: true
                    })
                  }
                }
              }
            }
          }
        }
      }
    })
  }

  onCopy(str, e) {
    e.stopPropagation()
    try {
      Taro.setClipboardData({
        data: str
      })
      if (process.env.TARO_ENV === 'h5') {
        Taro.showToast({title: '复制成功'})
      }
    } catch (e) {
      Taro.showToast({title: '复制失败'})
    }
  }

  render() {
    const {
      listForm,
      codeShow,
      ticketList,
    } = this.state
    return (
      <View className='appoint-order-root appoint-order-douyin'>
        <GzhAuth />
        <View className='wrap1 box no-padding-top' onClick={()=> { Taro.navigateTo({ url: '' }) }}>
          <View className='content' style='padding: 10px !important;'>
            <View className='pro-name'>{listForm.goodsMainNmae || ''}</View>
          </View>
        </View>
        <View className='wrap1 box'>
          <View className='title'>券号</View>
          {listForm.ticketList && listForm.ticketList.length > 0 && listForm.ticketList.map((item, index) => <View className='content'>
            <View className='left'>券码：</View>
            <View className='right'><Input type='text'
                                           disabled={true}
                                           placeholder='请填写正确的券号(预约码)'
                                           value={item.ticket}
            /></View>
          </View>)}
        </View>
        <View className='wrap1 box'>
          <View className='title'>客人信息</View>
          <View className='content'>
            <View className='left'>姓名：</View>
            <View className='right'>
              <Input type='text'
                     disabled={true}
                     value={listForm.real_name}
                     maxLength={15}
                     /></View>
          </View>
          <View className='content'>
            <View className='left'>电话：</View>
            <View className='right'>
              <Input type='text'
                     disabled={true}
                     value={listForm.phone}
                      /></View>
          </View>
        </View>
        <View className='wrap1 box'>
          <View className='content'>
            <View className='left'>数量：</View>
            <View className='right'>{listForm.ticketNumber}</View>
          </View>
        </View>

        <View
          className='addInfo'
          style={`background-color: ${process.env.mainColor}`}
          onClick={() => this.submit()}
        >确认兑换</View>

        {/*核验码弹窗*/}
        {codeShow && <View className='ticket-box-model' onClick={() => {this.setState({codeShow: false})}}>
          <View className='ticket-box-show_code_bj'/>
          <View className='ticket-box-show_code_content'>
            <View className='ticket-box-show_code_content-tip'>如码数量过多，可下滑查看更多</View>
            <View className='ticket-box-show-max-height'>
              {ticketList && ticketList.length > 0 && ticketList.map((item, index) => <View>
                <View className='ticket-box-t_ticket'
                      onClick={this.onCopy.bind(this, item.ticket)}
                >核验码:<Text selectable>{item.ticket}</Text>
                  <Image
                    className={`img img${process.env.TARO_ENV}`}
                    src='https://resource.ivcheng.com/upload/images/20210419/1618801235523_500.png'
                  />
                </View>
                <View
                  className='ticket-box-code-box'
                >
                  <Image className='qrimg'
                         src={BASE_URL + GET_IMG + item.ticket}
                  />
                </View>
              </View>)}
            </View>
            <View className='code-shuoming'>
              <View className='ticket-top-info-b-line' />
              <View className='code-shuoming-word'>
                <Text>凭此码去年票小程序兑换年卡</Text>
              </View>
            </View>
          </View>
        </View>}

      </View>
    )
  }
}
